package net.caixiaomi.info.ui.dialog;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.MatchFilterAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseDialogFragment;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.MatchItem;
import net.caixiaomi.info.util.Constants;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.R.id.button1;
import static android.R.id.button2;
import static android.R.id.list;
import static net.caixiaomi.info.util.EventWhat.EVENT_FOOTBALL_MATCH_FILTER;

/**
 * 赛事筛选
 */

public class MatchFilterDialogFragment extends BaseDialogFragment implements BaseQuickAdapter.OnItemClickListener {

    @BindView(list)
    RecyclerView mListView;
    @BindView(R.id.btn_only)
    TextView mBtnOnly;
    @BindView(R.id.plan)
    View mPlan;
    private int mPlanFilter;


    private MatchFilterAdapter mAdapter;
    private String mIsAlreadyBuyMatch = "";
    private List<MatchItem> mData = new ArrayList<>();

    @OnClick(R.id.all)
    void toSelectAll() {
        Iterator<MatchItem> data = mAdapter.getData().iterator();
        while (data.hasNext()) {
            MatchItem next = data.next();
            next.setSelect(true);
        }
        mAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.inverse)
    void toInverse() {
        Iterator<MatchItem> data = mAdapter.getData().iterator();
        while (data.hasNext()) {
            MatchItem next = data.next();
            next.setSelect(!next.isSelect());
        }
        mAdapter.notifyDataSetChanged();

    }

    @OnClick(R.id.five)
    void toFiveMatch() {
        Iterator<MatchItem> data = mAdapter.getData().iterator();
        while (data.hasNext()) {
            MatchItem next = data.next();
            next.setSelect(false);
        }
        String fiveMatchName = getString(R.string.C_FIVE_MATCH_NAME);
        data = mAdapter.getData().iterator();
        while (data.hasNext()) {
            MatchItem next = data.next();
            next.setSelect(fiveMatchName.contains(next.getLeagueAddr()));
        }
        mAdapter.notifyDataSetChanged();
    }

    @OnClick(button1)
    void toConfirm() {
        List<MatchItem> data = mAdapter.getData();

        JSONObject params = new JSONObject();
        params.put("isAlreadyBuyMatch", mBtnOnly.isSelected() ? "1" : "");
        params.put("data", data);
        EventBus.getDefault().post(new CommonEvent(EVENT_FOOTBALL_MATCH_FILTER, params.toString()));
        dismissAllowingStateLoss();
    }

    @OnClick(button2)
    void toCancel() {
        dismiss();
    }

    /**
     * 只看已购对阵
     */
    @OnClick(R.id.btn_only)
    void toOnlyBuy(View view) {
        view.setSelected(!view.isSelected());
        mBtnOnly.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), view.isSelected() ? R.color.white : R.color.secondary_text));
        if (view.isSelected()) {
            List<MatchItem> data = mAdapter.getData();
            for (MatchItem item : data) {
                item.setSelect(false);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected int layoutRes() {
        return R.layout.dialog_match_filter;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String strData = getArguments().getString("data");
        mPlanFilter = getArguments().getInt("planFilter", 0);
        mIsAlreadyBuyMatch = getArguments().getString("isAlreadyBuyMatch");
        List<MatchItem> data = JSON.parseObject(strData, new TypeToken<List<MatchItem>>() {
        }.getType());
        if (data != null && !data.isEmpty()) {
            mData.addAll(data);
        }
    }

    @Override
    protected void onViewCreated(@NonNull View view) {
        try {
            Window window = getDialog().getWindow();
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            window.setBackgroundDrawable(new ColorDrawable(0xff000000));
            getDialog().getWindow().setLayout((int) (dm.widthPixels * 0.85), getDialog().getWindow().getAttributes().height);
            boolean dealVersion = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);
            mPlan.setVisibility(mPlanFilter == 1 && dealVersion ? View.VISIBLE : View.GONE);
            if (mPlanFilter == 1) {
                boolean isAlreadyByMatch = TextUtils.equals(mIsAlreadyBuyMatch, "1");
                mBtnOnly.setSelected(isAlreadyByMatch);
                mBtnOnly.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), mBtnOnly.isSelected() ? R.color.white : R.color.secondary_text));
            }
            mListView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
            mListView.setHasFixedSize(true);
            mAdapter = new MatchFilterAdapter(R.layout.view_textview);
            mAdapter.setOnItemClickListener(this);
            mAdapter.setNewData(mData);
            mListView.setAdapter(mAdapter);
            mListView.measure(0, 0);
            int measuredHeight = mListView.getMeasuredHeight();
            int maxHeight = AppHelper.getScreenHeight(CommonApp.getInstance()) / 3;
            if (measuredHeight > maxHeight) {
                ViewGroup.LayoutParams layoutParams = mListView.getLayoutParams();
                layoutParams.height = maxHeight;
                layoutParams.width = (int) (AppHelper.getScreenWidth(CommonApp.getInstance()) * 0.83);
            }
            getDialog().setCanceledOnTouchOutside(false);
            getDialog().setCancelable(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            mBtnOnly.setSelected(false);
            mBtnOnly.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), mBtnOnly.isSelected() ? R.color.white : R.color.secondary_text));

            MatchItem matchItem = mAdapter.getData().get(position);
            matchItem.setSelect(!matchItem.isSelect());
            mAdapter.notifyItemChanged(position);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
